import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Dialog, DialogTitle, DialogContent, Button, FormControlLabel, Switch} from '@mui/material';
import "./Feeding.css";
import { jwtDecode } from "jwt-decode";


const AddSensorDataDialog = ({ open, onClose, fetchData }) => {
    const [value, setValue] = useState(0);
    const [sensorId, setSensorId] = useState("");
    const [sensorData, setSensorData] = useState([]);
    const [sensors, setSensors] = useState([]);
    const [dateTime, setDateTime] = useState(new Date());
    const [equipmentId, setEquipmentId] = useState(0);
    const [equipments, setEquipments] = useState([]);
    const [editTime, setEditTime] = useState(false);
    const [comment, setComment] = useState("");
    const [pool, setPool] = useState(false);



    const handleComment = (event) => {
        setComment(event.target.value);
    };


    useEffect(() => {
        fetchSensors();
        fetchEquipments();
        setDateTime(formatToLocalDatetime(new Date()));
    }, []);

    const handleDateTimeChange = (event) => {
        setDateTime(event.target.value);
    };
    


    const fetchSensors = async () => {
        try {
            const headers = {
                'Authorization': `Bearer ${localStorage.getItem('access')}`,
            };
            axios.get(`${process.env.REACT_APP_API_BASE_URL}/sensors`, {headers}).then((response) =>{
                setSensors(response.data.sensors);
                console.log(response.data.sensors)
            })
            
        } catch (error) {
            console.error('Error fetching sensors:', error);
        }
    };
    const fetchEquipments = async () => {
        try {
            const headers = {
                'Authorization': `Bearer ${localStorage.getItem('access')}`,
            };
            const response = await axios.get(`${process.env.REACT_APP_API_BASE_URL}/equipment`, {headers});
            setEquipments(response.data.equipments);
        } catch (error) {
            console.error('Error fetching уйгшзьутеы:', error);
        }
    };

    const addSensorData = async () => {
        if (window.confirm("Вы уверены, что хотите внести данные?")) {
            setPool(true)
         }
    };

    useEffect(() =>{
        if (pool){
            newSensor()
        }
    }, [pool])

    const newSensor = () =>{
        try {
            const newSensorData = {
                "value": value,
                "id_sensors": sensorId,
                "date_time": new Date().toISOString(), 
                'comment': comment 
            };
            const headers = {
                'Authorization': `Bearer ${localStorage.getItem('access')}`,
            };
            console.log(newSensorData)
            axios.post(`${process.env.REACT_APP_API_BASE_URL}/indication`, newSensorData, {headers}).then((response) => {
                fetchData();
                onClose();
            })
        } catch (error) {
            console.error('Error adding new sensor data:', error);
        }
    }

    const handleSensorChange = (event) => {
        setSensorId(event.target.value);
        let ids = event.target.value
        console.log(sensors.find(sensor => sensor.id == ids))
        setEquipmentId(sensors.find(sensor => sensor.id == ids) !== undefined? sensors.find(sensor => sensor.id == ids).id_equipment:0)
    };
    const handleEquipmentChange = (event) => {
        setEquipmentId(event.target.value);
    };

    const handleInputChangeValue = (event) => {
        setValue(event.target.value);
    };

    const toggleEditTime = () => {
        setEditTime(!editTime);
    };

    const formatToLocalDatetime = (date) => {
        const tzOffset = date.getTimezoneOffset() * 60000; // offset in milliseconds
        const localISOTime = new Date(date - tzOffset).toISOString().slice(0, 16);
        return localISOTime;
    };

    return (
        <Dialog open={open} onClose={onClose} sx={{ '& .MuiDialog-paper': { width: '80%', maxWidth: 'none' } }}>
            <DialogTitle>Добавить новые данные</DialogTitle>
            <DialogContent>
                <div>
                    <div className='input-table-container'>
                        <div style={{ display: 'grid', gridTemplateColumns: "0.2fr 1fr 0.2fr 1fr", gap: '20px' }}>
                             
                        <label>Датчик</label>
                            <select
                                value={sensorId}
                                onChange={handleSensorChange}
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            >
                                <option value={0}>Выберите датчик</option>
                                {sensors.map(sensor => (
                                    <option key={sensor.id} value={sensor.id}>{sensor.name}</option>
                                ))}
                            </select>
                            <label>Оборудование</label>
                            <input
                                value={(equipments.find(eq => eq.eid == equipmentId)) !== undefined && sensorId != 0? (equipments.find(eq => eq.eid == equipmentId)).ename: "" }
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%', maxWidth: "300px"}}
                                disabled
                            />  
                            <label>Значение</label>
                            <input
                                className='input-form-table'
                                type="number"
                                value={value}
                                onChange={handleInputChangeValue}
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%', }}
                            />                     
                        </div>
                        <div style={{ display: 'grid', gridTemplateColumns: "1.2fr 0.3fr 1fr", gap: '200px 20px' }}>
                            <FormControlLabel
                                control={
                                    <Switch
                                        checked={editTime}
                                        onChange={toggleEditTime}
                                    />
                                }
                                label="Хотите уточнить время измерения?"
                                sx={{
                                    '& .MuiFormControlLabel-label': {
                                        fontFamily: 'Montserrat', fontWeight: 'bolder',
                                    }
                                }}
                            />
                            <label>Время кормления</label>
                                <input
                                className='input-form-table'
                                    type="datetime-local"
                                    time
                                    value={dateTime}
                                    onChange={handleDateTimeChange}
                                    style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                                    disabled={!editTime}
                                />
                        </div>
                        <div style={{ display: 'grid', gridTemplateColumns: "0.2fr 1fr", gap: '10px' }}>
                            <label>Комментарий</label>
                            <textarea
                                className='input-form-table'
                                type="text"
                                value={comment}
                                onChange={handleComment}
                                style={{ borderColor: '#003AD0', margin: 0, width: '80%', maxWidth: '1400px' }}
                                required={true}
                            />
                        </div>
                        {sensorId && sensorId != 0 &&
                        <div style={{ display: 'grid', gridTemplateColumns: "0.5fr 1fr 0.5fr 1fr", gap: '20px' }}>
                            <label>Местоположение</label>
                            <p>{sensors.find(sensor => sensor.id == sensorId).location}</p>
                            <label>Единицы измерения</label>
                            <p>{sensors.find(sensor => sensor.id == sensorId).units}</p>
                            <label>Частота</label>
                            <p>{sensors.find(sensor => sensor.id == sensorId).frequency + " раз " + sensors.find(sensor => sensor.id == sensorId).dimension}</p>
                            <label>Рабочее состояние</label>
                            <p>{sensors.find(sensor => sensor.id == sensorId).min_operating_condition + "-" + sensors.find(sensor => sensor.id == sensorId).max_operating_condition}</p>
                            <label>Критическое состояние</label>
                            <p>{sensors.find(sensor => sensor.id == sensorId).min_critical_condition + "-" + sensors.find(sensor => sensor.id == sensorId).max_critical_condition}</p>
                            <label>Смертельное состояние</label>
                            <p>{"<" + sensors.find(sensor => sensor.id == sensorId).min_fatal_condition + " и >" + sensors.find(sensor => sensor.id == sensorId).max_fatal_condition}</p>
                            
                            {/* 
                        
                       </div>
                       <div style={{ display: 'grid', gridTemplateColumns: "0.5fr 1fr 0.5fr 1fr", gap: '20px' }}>

                            <label>Минимальное рабочее состояние</label>
                            <input
                                type="number"
                                value={minOperatingCondition}
                                onChange={handleNumberInputChange(setMinOperatingCondition)}
                                className="input-form-table"
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                       
                            <label>Максимальное рабочее состояние</label>
                            <input
                                type="number"
                                value={maxOperatingCondition}
                                onChange={handleNumberInputChange(setMaxOperatingCondition)}
                                className="input-form-table"
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                       </div>
                       <div style={{ display: 'grid', gridTemplateColumns: "0.5fr 1fr 0.5fr 1fr", gap: '20px' }}>

                            <label>Минимальное критическое состояние</label>
                            <input
                                type="number"
                                value={minCriticalCondition}
                                onChange={handleNumberInputChange(setMinCriticalCondition)}
                                className="input-form-table"
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                       
                            <label>Максимальное критическое состояние</label>
                            <input
                                type="number"
                                value={maxCriticalCondition}
                                onChange={handleNumberInputChange(setMaxCriticalCondition)}
                                className="input-form-table"
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                       </div>
                       <div style={{ display: 'grid', gridTemplateColumns: "0.5fr 1fr 0.5fr 1fr", gap: '20px' }}>

                            <label>Минимальное фатальное состояние</label>
                            <input
                                type="number"
                                value={minFatalCondition}
                                onChange={handleNumberInputChange(setMinFatalCondition)}
                                className="input-form-table"
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                       
                            <label>Максимальное фатальное состояние</label>
                            <input
                                type="number"
                                value={maxFatalCondition}
                                onChange={handleNumberInputChange(setMaxFatalCondition)}
                                className="input-form-table"
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                       </div>
                       
                            <div style={{ display: 'grid', gridTemplateColumns: "1.55fr 0.5fr 1fr", gap: '200px 20px' }}>
                            <FormControlLabel
                                control={
                                    <Switch
                                        checked={onOff}
                                        onChange={() => {setOnOff(!onOff)}}
                                    />
                                }
                                label={onOff? "Датчик включен":"Датчик выключен"}
                                sx={{ marginLeft:1,
                                    '& .MuiFormControlLabel-label': {
                                        fontFamily: 'Montserrat', fontWeight: 'bolder',
                                    }
                                }}
                            /> */}
                            </div>
}
                        <Button
                            onClick={addSensorData}
                            sx={{ margin: 3, width: '50%', color: 'white', borderRadius: '15px', backgroundColor: '#003AD0', '&:focus': { backgroundColor: '#003AD0' }, fontStyle: { fontColor: 'white', fontSize: 20, fontWeight: 'bolder', fontFamily: "Montserrat" } }}
                            variant={'contained'}
                        >
                            Сохранить
                        </Button>
                    </div>
                </div>
            </DialogContent>
        </Dialog>
    );
};

export default AddSensorDataDialog;
